#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define KEY 6
char *keyword[KEY] = {"for", "if", "then", "else", "while", "do"};
char id[1024];
int num;
int token;
int m;

void lexical(FILE *fp) {
	char x = getc(fp);

	num = 0;
	strcpy(id, "\0");
	
	int n=0;
	m=0;
	while((x==' ')||(x=='\n'))
	{
		x=getc(fp);
	}
    if(((x<='z')&&(x>='a'))||((x<='Z')&&(x>='A')))
      {
	   while(((x<='z')&&(x>='a'))||((x<='Z')&&(x>='A'))||((x>='0')&&(x<='9')))
      		{	
			  	id[m++]=x;
       			x=getc(fp);
			}
    	    ungetc(x, fp);
      		token=10;
      for(n=0;n<6;n++)
      {
      	if(strcmp(id,keyword[n])==0)
      	{
      		token=n+1;
      		break;
		  }
	  }	
	  }	
      else if((x>='0')&&(x<='9'))
      {
	   	while((x>='0')&&(x<='9'))
    	{ num=num*10+x-'0';
    	  x=getc(fp);
    	}
    	ungetc(x, fp);
   		 token=11;
      }
    else switch(x)
    {     
	case '<':
		  id[m++]=x;
          x=getc(fp);
           if(x=='=')
            {  token=22;
               id[m++]=x;
            }
            else if(x=='>')
            {
            	token=21;
            	id[m++]=x;
			}
          else
            {  token=20;
              ungetc(x, fp);
            }
          break;
     case '>':
	 	  id[m++]=x;
          x=getc(fp);
          if(x=='=')
            { token=24;
              id[m++]=x;
            }
          else
            { token=23;
              ungetc(x, fp);
            }
          break;
  	case ':':
	 	  id[m++]=x;
          x=getc(fp);
          if(x=='=')
            { token=18;
              id[m++]=x;
            }
          else
            { token=17;
             ungetc(x, fp);
            }
          break;
     case '+': 
            token=13;
            id[m++]=x;
          break;
     case '-':
             token=14;
            id[m++]=x;
          break;
     case '*': 
	 		token=15;
           	id[m++]=x;
           break;
     case '/': 
	 		token=16;
           	id[m++]=x;
           break;
     case '=':
	 	  token=25;
	 	  break;
     case ';': 
	 	  token=26;
          	id[m++]=x;
          break;
	 case '(': 
	 	   token=27;
           	id[m++]=x;
           break;
     case ')': 
	 	   token=28;
           id[m++]=x;
           break;
     case '#': 
	 	   token=0;
           id[m++]=x;
           break;
     default:
         break;
       }
    	id[m++]='\0';
    }
	
	//process x
	//process each regex here
	//store the result in global variables id, num, or token
	//in case of backtrack, use
	//ungetc(x, fp);	

int main(int argc, const char *argv[])
{
	/*if(argc < 2) {
		printf("insufficient args\n");
		return 1;
	}*/
	FILE *fp = fopen("test1.txt", "r");
	do {
		lexical(fp);
		switch(token) {
			case 10: printf("(id, %s)\n", id); break;
			case 11: printf("(num, %d)\n", num); break;
			case -1: printf("error!\n"); break;
			default: printf("(%d, %s)\n", token, id); 		
		}
	} while(token != 0);
	

	fclose(fp);
	return 0;
}

